import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  //对应我们登录的表单
  myForm: FormGroup;

  //输入用户名的输入控件
  userName: AbstractControl;

  //输入密码的输入控件
  password: AbstractControl;

  baseUrl='http://127.0.0.1:8080/';
  name$: Observable<string>;

  constructor(private fb: FormBuilder,private httpClient: HttpClient) {
    this.myForm = this.fb.group(
      {
        'userName': ['', Validators.compose([Validators.required, Validators.minLength(3),Validators.maxLength(20)])],
        'password': ['', Validators.compose([Validators.required, Validators.minLength(6),Validators.maxLength(16)])]
      }
    );

    this.userName = this.myForm.controls['userName'];
    this.password = this.myForm.controls['password'];
    this.name$=this.userName.valueChanges;
    this.userName.valueChanges.subscribe(val=>{
      console.log(val);
    })
  
  }
  onSubmit(value: any) {
    if(this.myForm.invalid){
      alert('表单无效！');
      return;
    }
    this.httpClient.post(this.baseUrl + 'login',this.myForm.value).subscribe(
      (val: any) => {//val是服务器返回的值
        if (val.succ) {
          alert('登录成功！');
          window.location.href="http://www.baidu.com";
        }else{
          alert('登录失败！');
        }
      }
    );
  }

}
